package com.alander.nexusgo.user.controller;

import com.alander.nexusgo.common.response.Result;
import com.alander.nexusgo.framework.web.starter.controller.BaseController;
import com.alander.nexusgo.user.service.UserService;
import com.alander.nexusgo.user.utils.IpUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;

/**
 * OAuth2登录控制
 */
@RestController
@RequestMapping("/api/auth/oauth2")
public class OAuth2Controller extends BaseController {

    @Autowired
    private UserService userService;
    
    @Value("${oauth2.frontend.callback-url}")
    private String frontendCallbackUrl;

    /**
     * 第三方登录重定向
     */
    @GetMapping("/login/{provider}")
    public Result<String> oauth2Login(@PathVariable(value = "provider") String provider, HttpServletResponse response) {
        // 重定向到第三方授权页面
        String redirectUrl = userService.getOAuth2RedirectUrl(provider);
        return success(redirectUrl);
    }

    /**
     * 第三方登录回调处理
     */
    @GetMapping("/callback/{provider}")
    public void oauth2Callback(
            @PathVariable(value = "provider") String provider,
            @RequestParam(value = "code") String code,
            @RequestParam(value = "state", required = false) String state,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        try {
            // 获取客户端IP
            String clientIp = IpUtil.getClientIpv4(request);
            // 处理第三方登录回调
            Map<String, Object> result = userService.handleOAuth2Callback(provider, code, state, clientIp);

            // 构建重定向URL（包含成功标志、token和state）
            String redirectUrl = frontendCallbackUrl + "/" + provider + "?success=true&token=" + result.get("token");
            if (state != null) {
                redirectUrl += "&state=" + state;
            }

            // 重定向到前端
            response.sendRedirect(redirectUrl);
        } catch (Exception e) {
            // 构建失败重定向URL
            String redirectUrl = frontendCallbackUrl + "/" + provider + "?success=false&error=" + e.getMessage();
            if (state != null) {
                redirectUrl += "&state=" + state;
            }

            // 重定向到前端
            response.sendRedirect(redirectUrl);
        }
    }


}